import service from './service.js'
import util from './util/util.js'

// 获取应用的基路径，默认/
var routerBase = '/'
var apiBaseURL = 'api/v1'

const httpRequest = {}
// get请求(获取数据) 只支持params传参
httpRequest.get = function ({ url, params, isReject = false, baseURL = apiBaseURL, isRouterBase = true }) {
    params = util.dataTrim(params)
    return new Promise((resolve, reject) => {
        service
            .get(url, { params, baseURL })
            .then(res => {
                resolve(res)
            })
            .catch(error => {
                if (isReject) reject(error)
            })
    })
}
// post请求(表单提交+文件上传) 同时支持data和params传参
httpRequest.post = function ({ url, data, params, isReject = false, baseURL = apiBaseURL, isRouterBase = true }) {
    data = util.dataTrim(data)
    params = util.dataTrim(params)
    return new Promise((resolve, reject) => {
        service
            .post(url, data, { params, baseURL })
            .then(res => {
                resolve(res)
            })
            .catch(error => {
                if (isReject) reject(error)
            })
    })
}
// put请求(更新所有数据推送到后端) 同时支持data和params传参
httpRequest.put = function ({ url, data, params, isReject = false, baseURL = apiBaseURL, isRouterBase = true }) {
    data = util.dataTrim(data)
    params = util.dataTrim(params)
    return new Promise((resolve, reject) => {
        service
            .put(url, data, { params, baseURL })
            .then(res => {
                resolve(res)
            })
            .catch(error => {
                if (isReject) reject(error)
            })
    })
}
// delete请求 单个时使用params传参 批量删除时使用data传参
httpRequest.delete = function ({ url, data, params, isReject = false, baseURL = apiBaseURL, isRouterBase = true }) {
    params = util.dataTrim(params)
    return new Promise((resolve, reject) => {
        service
            .delete(url, { data, params, baseURL })
            .then(res => {
                resolve(res)
            })
            .catch(error => {
                if (isReject) reject(error)
            })
    })
}
// patch请求(只将更改的数据推送到后端) 同时支持data和params传参
httpRequest.patch = function ({ url, data, params, isReject = false, baseURL = apiBaseURL, isRouterBase = true }) {
    data = util.dataTrim(data)
    params = util.dataTrim(params)
    return new Promise((resolve, reject) => {
        service
            .patch(url, data, { params, baseURL })
            .then(res => {
                resolve(res)
            })
            .catch(error => {
                if (isReject) reject(error)
            })
    })
}

export default httpRequest
